package com.powernode.springmvc.dao;

import com.powernode.springmvc.bean.User;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Repository
public class UserDao {
    private static List<User> users = new ArrayList<User>();

    static {
        User user1 = new User(1001L, "张三", 1, "zhangsan@qq.com");
        User user2 = new User(1002L, "李四", 1, "lisi@qq.com");
        User user3 = new User(1003L, "王五", 2, "wangwu@qq.com");
        User user4 = new User(1004L, "赵六", 1, "zhaoliu@qq.com");
        User user5 = new User(1005L, "jerry", 1, "jerry@qq.com");
        User user6 = new User(1006L, "小丽", 2, "xiaoli@qq.com");
        users.add(user1);
        users.add(user2);
        users.add(user3);
        users.add(user4);
        users.add(user5);
        users.add(user6);
    }

    public List<User> findAll() {
        return users;
    }

    public void addUser(User user) {
        User usersLast = users.getLast();
        Long id = usersLast.getId();
        user.setId(id + 1);
        users.add(user);
    }

    public User getUserById(Long id) {
        return users.stream().filter(user -> Objects.equals(user.getId(), id)).findFirst().get();
    }

    public void editUser(User user) {
        for (int i = 0; i < users.size(); i++) {
            if (users.get(i).getId().equals(user.getId())) {
                users.set(i, user);
                return;
            }
        }
    }

    public void deleteUser(Long id) {
        users.remove(users.stream().filter(user -> user.getId().equals(id)).findFirst().get());
    }
}
